Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- getMin() – Retrieve the minimum element in the stack.
Example:
1 | MinStack minStack = new MinStack(); |
Solution:
虽然这是一道简单题,但是并不简单。
- python
1 | class MinStack: |
这是最容易实现和想的一个方法,但是当stack存入太多item的时候,getMin将变得十分耗时,起码是O(n)的时间复杂度。如何解决?我们不如换个思路,当加入item的时候就记录下最小值。这里用到了动态规划的思想,最小值是,前一个数的最小值和当前数做比较来获得的。
1 | class MinStack: |
1 | class MinStack: |
和上面的异曲同工,但是没有调用内部函数